import * as step from '@flow-step/step-toolkit'
import * as fs from 'fs'
import path from 'path'
import fsPromises from 'fs/promises'

export async function setDependentFiles(targetDir: string){
    const currentDir = __dirname
    const copyList = ['builder','diff','report-template.html']
    for (const item of copyList) {
        copyDependency(path.join(currentDir,item), path.join(targetDir,item))
    }
    step.debug(`set permission for diff to 755`)
    fs.chmodSync(path.join(targetDir,'diff'), 0o755)
    step.debug(`set permission for builder to 755`)
    fs.chmodSync(path.join(targetDir,'builder'), 0o755)

    const resultCode = await step.exec.call("/bin/bash", ["-c", `tar -zxf ${path.join(currentDir, 'js-codescan.tar')} -C ${targetDir}`], {
        listener: {
            stdoutLine: (line: string) => step.infoV1(line),
            stderrLine: (line: string) => step.warnV1(line),
        },
    });
    if (resultCode !== 0) {
        throw new Error(`failed to extract js-codescan.tar to ${targetDir}, exitCode: ${resultCode}`)
    }
    step.debug(`js-codescan.tar was extracted to ${targetDir}`)
    step.debug(`set permission for code-quality-eslint to 755`)
    fs.chmodSync(path.join(targetDir,'code-quality-eslint'), 0o755)
}


export function copyDependency(source: string, target: string) {
    step.debug(`copy ${source} to ${target}`)
    // 检查目标文件是否存在
    if (fs.existsSync(target)) {
        step.debug(`remove ${target}`)
        fs.unlinkSync(target);
    }
    fs.copyFileSync(source, target)
}

export function findEslintrcFiles(dir: string){
    return fs.readdirSync(dir)
        .filter(file => file.startsWith('.eslintrc.'))
        .map(file => path.join(dir, file));
}

export async function readFile(filePath: string): Promise<string> {
    try {
        const data = await fsPromises.readFile(filePath, 'utf-8')
        return data
    } catch (error) {
        step.error(`Error reading file ${filePath}`)
        throw error
    }
}

